<?php
 
namespace App\Base;
 
use \EasySwoole\EasySwoole\Config;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Http\Session\Session;
use think\Template;
use EasySwoole\Session\AbstractSessionController;
 
/**
 * 视图控制器
 * Class ViewController
 * @author  : evalor <master@evalor.cn>
 * @package App
 */
abstract class ViewController extends AbstractSessionController
{
    private $view;
    protected $SETTING;
    protected $CORE_CONF;
    protected $FORWARD;
    protected $ISAJAX=false;
    protected $ISGET=true;
    protected $ISPOST=false;
    protected $REQUEST_URI='';
    protected $USERAGENT='';
    protected $MM='';
    protected $CC='';
    protected $AA='';

    protected function sessionHandler(): \SessionHandlerInterface
    {
        /*
         * 此处应该由连接池拿链接，否则实际生产会导致不断创建链接
         */

        //$redis=\App\Base\RedisUni::getInstance()->getLink();
        //return new \EasySwoole\Session\Test\RedisHandler($redis);
        return new \EasySwoole\Session\FileSessionHandler();
    }
    public function index(){

    }
     
    /**
     * 初始化模板引擎
     * ViewController constructor.
     * @param string   $actionName
     * @param Request  $request
     * @param Response $response
     */
    public function __construct()
    {
        parent::__construct();
        $this->init();
    }
    public function msg($code,$msg='',$url='',$data=[]){
        if(!$this->ISAJAX){
            if($code){
                if(!$msg) $msg='操作成功';
                $jump="location.href='{$url}';";
                if(!$url) $jump="window.history.back();";
                $html="<html><head><meta charset=\"utf-8\"></head><body>加载中...<script>alert('{$msg}');{$jump}</script></body></html>";
            }else{
                if(!$msg) $msg='操作失败';
                $html="<html><head><meta charset=\"utf-8\"></head><body>加载中...<script>alert('{$msg}');window.history.back();</script></body></html>";
            }
            $this->response()->write($html);
        }else{
            if($code){
                if(!$msg) $msg='操作成功';
            }else{
                if(!$msg) $msg='操作失败';
            }
            $d=[
                'code'=>(int) $code,
                'msg'=>$msg,
                'url'=>$url,
                'data'=>$data,
            ];
            $this->response()->write(json_encode($d));
        }
    }
    /**
     * 获取用户的真实IP
     * @param string $headerName 代理服务器传递的标头名称
     * @return string
     */
    protected function clientRealIP($headerName = 'x-real-ip')
    {
        $server = \EasySwoole\EasySwoole\ServerManager::getInstance()->getSwooleServer();
        $client = $server->getClientInfo($this->request()->getSwooleRequest()->fd);
        $clientAddress = $client['remote_ip'];
        $xri = $this->request()->getHeader($headerName);
        $xff = $this->request()->getHeader('x-forwarded-for');
        if ($clientAddress === '127.0.0.1') {
            if (!empty($xri)) {  // 如果有xri 则判定为前端有NGINX等代理
                $clientAddress = $xri[0];
            } elseif (!empty($xff)) {  // 如果不存在xri 则继续判断xff
                $list = explode(',', $xff[0]);
                if (isset($list[0])) $clientAddress = $list[0];
            }
        }
        return $clientAddress;
    }
    protected function input($name, $default = '') {
        $value = $this->request()->getRequestParam($name);
        return $value ?? $default;
    } 
    protected function get(){
        return $this->request()->getQueryParams();
    }
    protected function post(){
        return $this->request()->getParsedBody();
    }
    protected function cookie($name='', $default = ''){
        $value = $this->request()->getCookieParams($name);
        return $value ?? $default;
    }
    /**
     * 输出模板到页面
     * @param  string|null $template 模板文件
     * @param array        $vars 模板变量值
     * @param array        $config 额外的渲染配置
     * @author : evalor <master@evalor.cn>
     */
    public function fetch($template, $vars = [], $config = [])
    {
        ob_start();
        $this->view->fetch($template, $vars, $config);
        $content = ob_get_clean();
        $this->response()->write($content);
    }
     
    /**
     * @return Template
     */
    public function getView(): Template
    {
        return $this->view;
    }
     
    public function init()
    {
        $this->view             = new Template();
        $tempPath               = Config::getInstance()->getConf('TEMP_DIR');     # 临时文件目录
        $class_name_array       = explode('\\', static::class);
        $class_name_array_count = count($class_name_array);
        //$controller_path = $class_name_array[$class_name_array_count - 2] . DIRECTORY_SEPARATOR . $class_name_array[$class_name_array_count - 1] . DIRECTORY_SEPARATOR;
        $controller_path = $class_name_array[$class_name_array_count - 1] . DIRECTORY_SEPARATOR;
//        var_dump(static::class);
        $this->view->config([
                                'view_path' => EASYSWOOLE_ROOT . DIRECTORY_SEPARATOR . 'App' . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . $controller_path,
                                # 模板文件目录
                                'cache_path' => "{$tempPath}/templates_c/",               # 模板编译目录
                            ]);
         
//        var_dump(EASYSWOOLE_ROOT . DIRECTORY_SEPARATOR . 'App' . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . $controller_path);
    
        //载入core_enums
        require_once EASYSWOOLE_ROOT.'/App/Third/core_enums.php';
        //载入core_conf
        require_once EASYSWOOLE_ROOT.'/App/Third/core_conf.php';
        $this->CORE_CONF=new \core_conf();
    }

    protected function actionNotFound(?string $action)
    {
        $this->response()->withStatus(404);
        $file = EASYSWOOLE_ROOT.'/App/Views/Error/404.html';
        $this->response()->write(file_get_contents($file));
    }

    protected function onException(\Throwable $throwable):void
    {
        $this->response()->getBody()->truncate();
        $file = EASYSWOOLE_ROOT.'/App/Views/Error/500.html';
        $this->response()->write(file_get_contents($file));
    }

    protected function onRequest($action):?bool
	{
        //全局模板变量
        $this->SETTING=include EASYSWOOLE_ROOT.'/App/Setting/1.php';
        $this->getView()->assign(['SETTING'=>$this->SETTING]);
        //forward
        $headers=$this->request()->getHeaders();
        $FORWARD=$this->request()->getRequestParam('FORWARD');
        if($FORWARD){
            $this->FORWARD=urldecode($FORWARD);
        }else{
            $this->FORWARD=(isset($headers['referer']) && $headers['referer'][0]) ? $headers['referer'][0] : '';
        }
        $this->getView()->assign(['FORWARD'=>$this->FORWARD,'CORE_CONF'=>$this->CORE_CONF]);
        
        //ISAJAX
        if(isset($headers['x-requested-with']) && $headers['x-requested-with'][0]=='XMLHttpRequest'){
            $this->ISAJAX=true;
        }

        $server=$this->request()->getServerParams();
        $this->REQUEST_URI=$server['request_uri'];
        
        $this->USERAGENT=isset($headers['user-agent'][0])?$headers['user-agent'][0]:'';

        $r=explode('/',trim($this->REQUEST_URI,'/'));
        isset($r[0]) or $r[0]='index';
        isset($r[1]) or $r[1]='index';
        $this->MM=strtolower($r[0]);
        $this->CC=strtolower($r[0]);
        $this->AA=strtolower($r[1]);
        
        $this->getView()->assign(['REQUEST_URI'=>$server['request_uri'],'MM'=>$this->MM,'CC'=>$this->CC,'AA'=>$this->AA]);

        $this->ISGET=$server['request_method']=='GET';
        $this->ISPOST=$server['request_method']=='POST';

        /*
array(10) {
  ["request_method"]=>
  string(4) "POST"
  ["request_uri"]=>
  string(26) "/frameset/set_menu_current"
  ["path_info"]=>
  string(26) "/frameset/set_menu_current"
  ["request_time"]=>
  int(1577087276)
  ["request_time_float"]=>
  float(1577087276.7704)
  ["server_protocol"]=>
  string(8) "HTTP/1.1"
  ["server_port"]=>
  int(9501)
  ["remote_port"]=>
  int(39082)
  ["remote_addr"]=>
  string(9) "127.0.0.1"
  ["master_time"]=>
  int(1577087276)
}

        */
	    return true;
    }
    protected function p($var){
        $this->response()->write(var_export($var,true));
    }
    protected function success($msg='',$url=''){
        $this->msg(1,$msg,$url);
    }
    protected function error($msg='',$url=''){
        $this->msg(0,$msg,$url);
    }

     
}